package com.lhs.Page;

import lombok.Data;

import java.io.Serial;
import java.util.List;
import java.util.Objects;
import com.baomidou.mybatisplus.core.metadata.IPage;

import javax.validation.constraints.Min;
import java.io.Serializable;


/**
 * 通用分页返回对象
 */
@Data
public class PageResult<T> implements Serializable {
    @Serial
    private static final long serialVersionUID = 1L;

    /** 当前页码 */
    @Min(value = 1, message = "当前页码不能小于1")
    private long current = 1;
    /** 每页数量 */
    private long size ;
    /** 总页数 */
    private long pages;
    /** 总记录数 */
    private long total;
    /** 当前页数据 */
    private List<T> records;

    public PageResult(long current, long size, long pages, long total, List<T> records) {
        // 参数校验
        if (current < 1) {
            throw new IllegalArgumentException("当前页码不能小于1");
        }
        if (size < 0) {
            throw new IllegalArgumentException("每页数量不能为负数");
        }

        this.current = current;
        this.size = size == 0 ? 10 : size; // 默认每页10条
        this.pages = pages < 0 ? 0 : pages;
        this.total = total < 0 ? 0 : total;
        this.records = records;
    }

    /**
     * 从 IPage 构建 PageResult 实例
     *
     * @param page IPage 对象
     * @return PageResult 实例
     */
    public static <T> PageResult<T> of(IPage<T> page) {
        if (page == null) {
            throw new IllegalArgumentException("IPage 参数不能为空");
        }
        return new PageResult<>(
                page.getCurrent(),
                page.getSize(),
                page.getPages(),
                page.getTotal(),
                page.getRecords()
        );
    }
}
